package online.xuping.center.ai;

import cn.hutool.core.util.CharsetUtil;
import cn.hutool.http.Header;
import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONUtil;
import cn.hutool.setting.Setting;
import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

/**
 * 类描述:    .
 *
 * @author xuping
 * 创建时间:  [2023/6/16 13:38]
 */
@Data
@Service
public class BaiduTokenServiceImpl {
    @Value("${baidu.cid}")
    private String cid;
    @Value("${baidu.cs}")
    private String cs;

    public BaiduTokenServiceImpl(String cid, String cs) {
        this.cid = cid;
        this.cs = cs;
    }

    public BaiduTokenServiceImpl() {
        Setting setting = new Setting("config/ai.setting" , CharsetUtil.CHARSET_UTF_8, true);
        this.cid = setting.getStr("cid");
        this.cs = setting.getStr("cs");
    }

    public String token() {
        try {
            String result2 = HttpRequest.get("https://aip.baidubce.com/oauth/2.0/token?client_id=" +
                            cid + "&client_secret=" + cs
                            + "&grant_type=client_credentials")
                    .header(Header.ACCEPT, "application/json")//头信息，多个头信息多次调用此方法即可
                    .header(Header.CONTENT_TYPE, "application/json")

                    .timeout(20000)//超时，毫秒
                    .execute().body();
            return JSONUtil.parseObj(result2).getStr("access_token");
        } catch (Exception e) {
            throw BaiduErrorCodeEnum.CAN_NOT_GET_TOKEN.exception();
        }
    }
}
